<?php
/**
 * Created by PhpStorm.
 * User: vanity
 * Date: 2018/1/5
 * Time: 9:43
 */
namespace Admin\Model;
use Think\Model;
class RoleUserModel extends Model
{
    protected $tableName='role_user';

    public function changeRole($user_id,$role_id)
    {
        $map = array('user_id'=>$user_id);
        $res = $this->where($map)->find();
        if(($res && $res['role_id'] == $role_id)||(!$res && !$role_id)){
            return true;
        }
        if($res){
            if(empty($role_id)){
                $result = $this->where($map)->delete();
            }else{
                $result = $this->data(array('role_id'=>$role_id))->where($map)->save();
            }
        }else{
            if(!empty($role_id)){
                $map['role_id'] = $role_id;
                $result = $this->add($map);
            }
        }
        return $result;
    }
    public function getPermissionPath($id)
    {
        $role_id = $this->where('user_id = '.$id)->getField('role_id');
        if(empty($role_id)){
            return 'all permission';
        }
        $permission_id = D('PermissionRole')->where('role_id = '.$role_id)->getField('permission_id',true);
        if(empty($permission_id)){
            return 'all permission';
        }
        $permission = M('permissions')->where(array('id'=>array('in',$permission_id)))->getField('name',true);
        return $permission;
    }
}